<script setup lang="ts">
import type { AppLogo } from '@/apis'
import type { FormInstance } from 'ant-design-vue'
import { projectSettingApis } from '@/apis'
import { useValidate } from '@/hooks'
import http from '@/utils/http'
import { KProModal, KProUpload, KProUserAvatar, useProModal } from '@king-one/antdv'
import { Empty, Form, message } from 'ant-design-vue'

interface FormState {
  fileId: string
  logoName: string
}

const { onFieldChange } = Form.useInjectFormItemContext()
const { modalVisible } = useProModal()
const { validateEnNum } = useValidate()

const formState = reactive<FormState>({
  fileId: '',
  logoName: '',
})

const list = ref<AppLogo[]>([])
const fileList = ref<{ id: string }[]>([])
const formRef = ref<FormInstance>()
const loading = ref(false)
const spinning = ref(false)
const avatarRefs = ref<any[]>([])

watch(fileList, (newVal) => {
  if (newVal.length > 0) {
    formState.fileId = newVal[0].id as string
  }
  else {
    formState.fileId = ''
  }
  onFieldChange()
})

function validateIconName(_: any, value: any, callback: any) {
  if (validateEnNum(value)) {
    callback(new Error('请输入英文和数字'))
  }
  else {
    callback()
  }
}

function onPreview(index: number) {
  avatarRefs.value[index].handlePreview()
}

function getImgUrl(imgName: string) {
  const url = `${import.meta.env.VITE_IMG_PRIFIX}${imgName}`
  return url
}

function onDisable(item: AppLogo) {
  projectSettingApis.disableAppIcon(item.fileId).then((res) => {
    if (res.status === 0) {
      message.success('禁用成功')
      getAppIconList()
    }
  })
}

function onEnable(item: AppLogo) {
  projectSettingApis.enableAppIcon(item.fileId).then((res) => {
    if (res.status === 0) {
      message.success('启用成功')
      getAppIconList()
    }
  })
}
function onConfirm() {
  formRef.value?.validate().then(async (res) => {
    if (res) {
      loading.value = true
      projectSettingApis.saveAppIcon(formState).then((res) => {
        if (res.status === 0) {
          message.success(`${formState.logoName}图标新增成功～`)
          modalVisible.value = false
          formRef.value?.resetFields()
          fileList.value = []
          getAppIconList()
        }
      }).finally(() => {
        loading.value = false
      })
    }
  }).catch((err) => {
    console.log(err)
  })
}

function onCancel() {
  formRef.value?.resetFields()
  fileList.value = []
  modalVisible.value = false
}

function getAppIconList() {
  spinning.value = true
  projectSettingApis.getAppIconList().then((res) => {
    if (res.status === 0) {
      list.value = res.data
    }
  }).finally(() => {
    spinning.value = false
  })
}

getAppIconList()
</script>

<template>
  <div class="app-icon-setting">
    <a-spin :spinning="spinning">
      <div>
        <a-card class="w-full h-[calc(100vh-150px)] overflow-y-auto">
          <div flex justify-end>
            <div class="w-500px flex justify-end">
              <a-button type="primary" shape="circle" @click="modalVisible = true">
                <template #icon>
                  <CloudUploadOutlined />
                </template>
              </a-button>
            </div>
          </div>
          <a-row v-if="list.length > 0" :gutter="[24, 36]" class="flex items-center mt-48px">
            <a-col v-for="(item, index) in list" :key="item.fileId" :xs="12" :sm="8" :md="6" :lg="3" :xl="3" class="icon-col flex-center-col">
              <div class="flex-center-col relative">
                <div class="icon-mark absolute w-100px h-130px bg-[rgba(0,0,0,0.7)] z-10 rounded-8px">
                  <div class="flex-center-col content-between h-100%">
                    <a-tooltip title="预览" @click="onPreview(index)">
                      <a-button shape="circle">
                        <template #icon>
                          <EyeOutlined />
                        </template>
                      </a-button>
                    </a-tooltip>

                    <a-tooltip v-if="item.enable" title="禁用">
                      <a-button shape="circle" class="mt-12px mb-12px" @click="onDisable(item)">
                        <template #icon>
                          <CloseCircleOutlined />
                        </template>
                      </a-button>
                    </a-tooltip>

                    <a-tooltip v-else title="启用">
                      <a-button shape="circle" class="mt-12px mb-12px" @click="onEnable(item)">
                        <template #icon>
                          <CheckCircleOutlined />
                        </template>
                      </a-button>
                    </a-tooltip>
                  </div>
                </div>
                <KProUserAvatar
                  :ref="el => { avatarRefs[index] = el }"
                  :avatar="getImgUrl(item.logoName)"
                  size="large"
                  round="15px"
                  style="width: 55px;height: 55px;"
                />
                <div class="pt-6px text-12px color-[var(--font-size-base)] truncate w-100px text-center">
                  {{ item.logoName }}
                </div>
                <a-tag v-if="!item.enable" class="absolute top-20px left-24px" color="#f50" :bordered="false">
                  已禁用
                </a-tag>
              </div>
            </a-col>
          </a-row>
          <a-empty v-else class="mt-100px" :image="Empty.PRESENTED_IMAGE_SIMPLE" />
        </a-card>
      </div>
    </a-spin>

    <KProModal
      v-model="modalVisible"
      title="应用Icon上传"
      width="700px"
      :modal-props="{
        confirmLoading: loading,
      }"
      @on-confirm="onConfirm"
      @on-cancel="onCancel"
    >
      <div class="w-450px m-auto">
        <a-form ref="formRef" :model="formState" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
          <a-form-item label="Icon名称" name="logoName" :rules="[{ required: true, message: '请输入 Icon 名称' }, { validator: validateIconName }]">
            <a-input v-model:value="formState.logoName" placeholder="请输入Icon名称" />
          </a-form-item>
          <a-form-item label="Icon图标" name="fileId" :rules="[{ required: true, message: '请上传 Icon 图标' }]">
            <KProUpload
              v-model:file-list="fileList"
              :http="http"
              business="test"
              proxy-prefix="/"
              upload-name="upload-1"
              prefix="/qy-file"
              :max-count="1"
              :max-size="0.02"
            />
            <p class="text-12px color-#999 pt-6px">
              图标支持 png、jpg、jpeg、gif，且大小不能超过 20kb
            </p>
          </a-form-item>
        </a-form>
      </div>
    </KProModal>
  </div>
</template>

<style scoped lang="less">
.icon-mark {
  display: none;
}

.icon-col:hover  {
  .icon-mark {
    display: block;
    transition: all 0.8s;
  }
}
</style>
